package sip

import (
	"bytes"
    "context"
	"crypto/md5"
	"encoding/hex"
	"encoding/xml"
	"fmt"
	"math/rand"
	"net"
	"strings"
	"time"

	"sipserver/device"
    "sipserver/media"

    "gopkg.in/yaml.v3"
    "io/ioutil"
)

// SIPServer 是 SIP 服务器结构体
type SIPServer struct {
	conn      *net.UDPConn
	devices   map[string]*device.Device // 存储已注册的设备
    platfrom  map[string]*device.DevicePlatfrom
	heartbeats map[string]time.Time    // 存储设备的心跳时间
	nonceMap  map[string]string         // 存储设备的 nonce 值
	inviteRespChan chan string          // 用于传递 INVITE 响应的通道
	optionsRespChan chan string      	// 用于传递 OPTION 响应的通道
	messageRespChan chan string			// 用于传递 MESSAGE 响应的通道 
    ackRespChan chan string             // 用于传递 ACK 响应的通道
	mediaEndChan   chan string
    cancel map[string]context.CancelFunc
    rtpServers     map[string]*net.UDPConn
}

// NewSIPServer 创建一个新的 SIP 服务器
func NewSIPServer(addr string) (*SIPServer, error) {
	udpAddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return nil, err
	}
	conn, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		return nil, err
	}
	return &SIPServer{
		conn:      conn,
		devices:   make(map[string]*device.Device),
        platfrom:  make(map[string]*device.DevicePlatfrom),
		heartbeats: make(map[string]time.Time),
		nonceMap:  make(map[string]string),
        cancel: make(map[string]context.CancelFunc),
	}, nil
}

type Config struct {
    Database struct {
        Host     string `yaml:"host"`
        Port     int    `yaml:"port"`
        Username string `yaml:"username"`
        Password string `yaml:"password"`
        Area string `yaml:"area"`
    } `yaml:"database"`
    Server struct {
        Address string `yaml:"address"`
        Port    int    `yaml:"port"`
    } `yaml:"server"`
}

// 定义配置结构体实例
var config Config

// Start 启动 SIP 服务器
func (s *SIPServer) Start() {

    ReadRunSetting()

	fmt.Println("SIP server started on", s.conn.LocalAddr())
	buf := make([]byte, 1024)

	s.devices[config.Database.Username] = &device.Device{
		ID:     config.Database.Username,
		IP:     config.Database.Host,
		Port:   config.Database.Port,
		Status: "Online",
	}

	for {
		n, addr, err := s.conn.ReadFromUDP(buf)
		if err != nil {
			fmt.Println("Error reading from UDP:", err)
			continue
		}
		go s.handleMessage(buf[:n], addr)
	}
}

func ReadRunSetting(){
        // 读取 YAML 文件
        yamlFile, err := ioutil.ReadFile("./api/device.yaml")
        if err != nil {
            fmt.Println("读取 YAML 文件时出错: %v", err)
        }
    
        // 解析 YAML 数据到结构体
        err = yaml.Unmarshal(yamlFile, &config)
        if err != nil {
            fmt.Println("解析 YAML 数据时出错: %v", err)
        }
    
        // 输出解析结果
        fmt.Printf("SIP主机: %s\n", config.Database.Host)
        fmt.Printf("SIP端口: %d\n", config.Database.Port)
        fmt.Printf("SIP服务器ID: %s\n", config.Database.Username)
        fmt.Printf("SIP服务器密码: %s\n", config.Database.Password)
        fmt.Printf("SIP服务器域: %s\n", config.Database.Area)
        fmt.Printf("主服务器地址: %s\n", config.Server.Address)
        fmt.Printf("主服务器端口: %d\n", config.Server.Port)
}

// handleMessage 处理接收到的 SIP 消息
func (s *SIPServer) handleMessage(data []byte, addr *net.UDPAddr) {
	msg := string(data)
	//fmt.Printf("Received SIP message from %s:\n%s\n", addr.String(), msg)

	// 检查是否为 INVITE 响应
	if strings.Contains(msg, "INVITE") {
        // 将 INVITE 响应发送到通道
        if s.inviteRespChan != nil {
            s.inviteRespChan <- msg
        }
        return
    }

	// 检查是否为 OPTIONS 响应
	if strings.Contains(msg, "OPTIONS") && strings.Contains(msg, "200 OK") {
		// 将 OPTIONS 响应发送到通道
		if s.optionsRespChan != nil {
			s.optionsRespChan <- msg
		}
		return
	}

    // 检查是否为 ACK 响应
	if strings.Contains(msg, "ACK") {
		// 将 OPTIONS 响应发送到通道
		if s.ackRespChan != nil {
			s.ackRespChan <- msg
		}
		return
	}

	// 检查是否为 MESSAGE 响应
	if strings.Contains(msg, "MESSAGE") && !strings.Contains(msg, "Keepalive") {
		// 将 OPTIONS 响应发送到通道
		if s.messageRespChan != nil {
			s.messageRespChan <- msg
		}
		return
	}

    if strings.Contains(msg, "INVITE") && !strings.Contains(msg, "Keepalive") {
		// 将 OPTIONS 响应发送到通道
		if s.inviteRespChan != nil {
			s.inviteRespChan <- msg
		}
		return
	}

	// 解析 SIP 消息
	if strings.Contains(msg, "REGISTER") {
		s.handleRegister(msg, addr)
	} else if strings.Contains(msg, "MESSAGE") && strings.Contains(msg, "MANSCDP+xml") {
		s.handleHeartbeat(msg, addr)
	}
}

// handleRegister 处理设备注册
func (s *SIPServer) handleRegister(msg string, addr *net.UDPAddr) {
	// 解析设备 ID
	deviceID := extractDeviceID(msg)
	if deviceID == "" {
		fmt.Println("Failed to extract device ID from REGISTER message")
		return
	}

	// 检查是否已经认证
	if strings.Contains(msg, "Authorization:") {
		// 设备已经发送了认证信息，验证认证信息
		if s.verifyAuthorization(msg, deviceID) {
			// 认证成功，注册设备
			device.RegisterDevice(deviceID, addr.IP.String(), addr.Port)
			s.devices[deviceID] = &device.Device{
				ID:     deviceID,
				IP:     addr.IP.String(),
				Port:   addr.Port,
				Status: "Online",
			}
			// 发送 200 OK 响应
			response := buildResponse(msg, 200, "OK")
			s.conn.WriteToUDP([]byte(response), addr)
			fmt.Printf("Device %s registered successfully\n", deviceID)

            OnceRegister(deviceID, addr.IP.String(), addr.Port)

		} else {
			// 认证失败，发送 403 Forbidden 响应
			response := buildResponse(msg, 403, "Forbidden")
			s.conn.WriteToUDP([]byte(response), addr)
			fmt.Printf("Device %s authentication failed\n", deviceID)
		}
	} else {
		// 设备未认证，发送 401 Unauthorized 响应
		nonce := generateNonce()
		s.nonceMap[deviceID] = nonce
		response := buildUnauthorizedResponse(msg, nonce)
		s.conn.WriteToUDP([]byte(response), addr)
		fmt.Printf("Sent 401 Unauthorized to device %s\n", deviceID)
	}
}

// verifyAuthorization 验证设备的认证信息
func (s *SIPServer) verifyAuthorization(msg, deviceID string) bool {
	// 提取 Authorization 字段
	fmt.Println("verifyAuthorization msg : "+msg)
	authHeader := extractHeader(msg, "Authorization:")
	if authHeader == "" {
		return false
	}
	fmt.Println("get authHeader ")
	// 解析 Authorization 字段
	username := extractAuthParam(authHeader, "username")
	realm := extractAuthParam(authHeader, "realm")
	nonce := extractAuthParam(authHeader, "nonce")
	uri := extractAuthParam(authHeader, "uri")
	response := extractAuthParam(authHeader, "response")

	// 验证 nonce 是否匹配
	if nonce != s.nonceMap[deviceID] {
		return false
	}

	// 计算期望的 response 值
	expectedResponse := calculateMD5(username, realm, config.Database.Password, nonce, uri)
	return response == expectedResponse
}

func OnceRegister(deviceId string, clientIP string, clientPort int) {

    user := device.DeviceBasic{}
    user.DeviceID = deviceId
    user.ClientIP = clientIP
    user.ClientPort = clientPort

    data := device.FindDeviceByName(user.DeviceID)
    if data.DeviceID != "" {
        return
    }

    user.Salt = "no_organization"
    device.CreateDevice(user)

}

// buildResponse 构建 SIP 响应消息
func buildResponse(msg string, code int, reason string) string {
	via := extractHeader(msg, "Via:")
	from := extractHeader(msg, "From:")
	to := extractHeader(msg, "To:")
	callID := extractHeader(msg, "Call-ID:")
	cSeq := extractHeader(msg, "CSeq:")

	var buffer bytes.Buffer
	buffer.WriteString(fmt.Sprintf("SIP/2.0 %d %s\r\n", code, reason))
	buffer.WriteString(fmt.Sprintf("%s\r\n", via))
	buffer.WriteString(fmt.Sprintf("%s\r\n", from))
	buffer.WriteString(fmt.Sprintf("%s\r\n", to))
	buffer.WriteString(fmt.Sprintf("%s\r\n", callID))
	buffer.WriteString(fmt.Sprintf("%s\r\n", cSeq))
	buffer.WriteString("Content-Length: 0\r\n\r\n")
	return buffer.String()
}

// buildUnauthorizedResponse 构建 401 Unauthorized 响应
func buildUnauthorizedResponse(msg, nonce string) string {
	via := extractHeader(msg, "Via:")
	from := extractHeader(msg, "From:")
	to := extractHeader(msg, "To:")
	callID := extractHeader(msg, "Call-ID:")
	cSeq := extractHeader(msg, "CSeq:")

	var buffer bytes.Buffer
	buffer.WriteString("SIP/2.0 401 Unauthorized\r\n")
	buffer.WriteString(fmt.Sprintf("%s\r\n", via))
	buffer.WriteString(fmt.Sprintf("%s\r\n", from))
	buffer.WriteString(fmt.Sprintf("%s\r\n", to))
	buffer.WriteString(fmt.Sprintf("%s\r\n", callID))
	buffer.WriteString(fmt.Sprintf("%s\r\n", cSeq))
	buffer.WriteString(fmt.Sprintf("WWW-Authenticate: Digest realm=\"5100000000\", nonce=\"%s\", algorithm=MD5\r\n", nonce))
	buffer.WriteString("Content-Length: 0\r\n\r\n")
	return buffer.String()
}

// extractDeviceID 从 SIP 消息中提取设备 ID
// func extractDeviceID(msg string) string {
// 	fromHeader := extractHeader(msg, "From:")
// 	if fromHeader == "" {
// 		return ""
// 	}
// 	parts := strings.Split(fromHeader, ":")
// 	if len(parts) < 2 {
// 		return ""
// 	}
// 	return strings.TrimSpace(parts[1])
// }

func extractDeviceID(msg string) string {
    fromHeader := extractHeader(msg, "From:")
    if fromHeader == "" {
        return ""
    }
    // 先去掉 "From: " 部分
    fromValue := strings.TrimPrefix(fromHeader, "From: ")
    // 找到 < 和 > 之间的内容
    start := strings.Index(fromValue, "<")
    end := strings.Index(fromValue, ">")
    if start == -1 || end == -1 || start >= end {
        return ""
    }
    sipURI := fromValue[start+1 : end]
    // 从 SIP URI 中提取设备 ID
    parts := strings.Split(sipURI, "@")
    if len(parts) < 1 {
        return ""
    }
    // 去掉 "sip:" 前缀
    deviceID := strings.TrimPrefix(parts[0], "sip:")
    return deviceID
}

// extractHeader 从 SIP 消息中提取指定头部字段
func extractHeader(msg, header string) string {
	lines := strings.Split(msg, "\r\n")
	for _, line := range lines {
		if strings.HasPrefix(line, header) {
			return line
		}
	}
	return ""
}

// extractAuthParam 从 Authorization 字段中提取指定参数
func extractAuthParam(authHeader, param string) string {
	parts := strings.Split(authHeader, ",")
	for _, part := range parts {
		if strings.Contains(part, param) {
			kv := strings.Split(part, "=")
			if len(kv) == 2 {
				return strings.Trim(kv[1], "\"")
			}
		}
	}
	return ""
}

// generateNonce 生成一个随机的 nonce 值
func generateNonce() string {
	rand.Seed(time.Now().UnixNano())
	nonce := make([]byte, 16)
	rand.Read(nonce)
	return hex.EncodeToString(nonce)
}

// calculateMD5 计算 MD5 摘要
func calculateMD5(username, realm, password, nonce, uri string) string {
	ha1 := fmt.Sprintf("%s:%s:%s", username, realm, password)
	ha2 := fmt.Sprintf("REGISTER:%s", uri)
	response := fmt.Sprintf("%s:%s:%s", md5Hash(ha1), nonce, md5Hash(ha2))
	return md5Hash(response)
}

// md5Hash 计算字符串的 MD5 值
func md5Hash(input string) string {
	hash := md5.Sum([]byte(input))
	return hex.EncodeToString(hash[:])
}

// handleHeartbeat 处理心跳消息
func (s *SIPServer) handleHeartbeat(msg string, addr *net.UDPAddr) {
    // 解析设备 ID
    deviceID := extractDeviceID(msg)
    if deviceID == "" {
        fmt.Println("Failed to extract device ID from HEARTBEAT message")
        return
    }

	fmt.Println("get deviceID : "+deviceID)

    // 更新心跳时间
    s.heartbeats[deviceID] = time.Now()

    // 发送 200 OK 响应
    response := buildResponse(msg, 200, "OK")
    _, err := s.conn.WriteToUDP([]byte(response), addr)
    if err != nil {
        fmt.Println("Failed to send HEARTBEAT response:", err)
        return
    }
    fmt.Printf("Heartbeat received from device %s\n", deviceID)
}

// extractDeviceID 从 SIP 消息中提取设备 ID
// func extractDeviceID(msg string) string {
// 	lines := strings.Split(msg, "\r\n")
// 	for _, line := range lines {
// 		if strings.HasPrefix(line, "From:") {
// 			parts := strings.Split(line, ":")
// 			if len(parts) > 1 {
// 				return strings.TrimSpace(parts[1])
// 			}
// 		}
// 	}
// 	return ""
// }

// // buildResponse 构建 SIP 响应消息
// func buildResponse(deviceID, method string, code int, reason string) string {
// 	var buffer bytes.Buffer
// 	buffer.WriteString(fmt.Sprintf("SIP/2.0 %d %s\r\n", code, reason))
// 	buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s\r\n", deviceID))
// 	buffer.WriteString(fmt.Sprintf("From: <sip:%s>\r\n", deviceID))
// 	buffer.WriteString(fmt.Sprintf("To: <sip:%s>\r\n", deviceID))
// 	buffer.WriteString(fmt.Sprintf("Call-ID: %s\r\n", deviceID))
// 	buffer.WriteString(fmt.Sprintf("CSeq: 1 %s\r\n", method))
// 	buffer.WriteString("Content-Length: 0\r\n\r\n")
// 	return buffer.String()
// }

// Invite 发起音视频播放请求
func (s *SIPServer) Invite(deviceID, mediaURL string) error {
    device, exists := s.devices[deviceID]
    if !exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 1. 构建 INVITE 消息
    inviteMsg := buildInviteMessage(deviceID, mediaURL,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    fmt.Println("inviteMsg : " + inviteMsg)

    // 2. 发送 INVITE 消息
    _, err := s.conn.WriteToUDP([]byte(inviteMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send INVITE message: %v", err)
    }
    fmt.Printf("INVITE message sent to device %s\n", deviceID)

    // 3. 创建通道用于接收 INVITE 响应
    s.inviteRespChan = make(chan string)

    // 4. 等待并接收 INVITE 响应
    for {
        select {
        case response := <-s.inviteRespChan:
            fmt.Printf("Received INVITE response from device %s:\n %s\n", deviceID, response)
    
            // 5. 检查摄像头响应
            if strings.Contains(response, "200 OK") {
    
                // 6. 发送 ACK 确认消息
                ackMsg := buildAckMessage(deviceID, response)
                _, err = s.conn.WriteToUDP([]byte(ackMsg), addr)
                if err != nil {
                    return fmt.Errorf("failed to send ACK message: %v", err)
                }
                fmt.Printf("ACK message sent to device %s\n", deviceID)
                fmt.Println("ackMsg:"+ackMsg)
    
                // 7. 启动 RTP 服务器接收媒体流
                // ctx, cancel := context.WithCancel(context.Background())
                // s.cancel[deviceID] = cancel
                // go s.startRTPServer(deviceID,ctx)
                
                ctx, cancel := context.WithCancel(context.Background())
                s.cancel[deviceID] = cancel
                go media.StartRTPServerD(deviceID, ctx)

                break
                
            }
    
            fmt.Printf("device %s rejected the INVITE request: %s", deviceID, response)
    
            case <-time.After(10 * time.Second): // 设置超时时间为 10 秒
                return fmt.Errorf("timeout waiting for INVITE response from device %s", deviceID)
        }
    }

    // 8. 关闭通道
    // close(s.inviteRespChan)
    // s.inviteRespChan = nil

    return nil
}

// StopStream 方法用于停止音视频流
func (s *SIPServer) StopStream(deviceID, callID string) error {
    device, exists := s.devices[deviceID]
    if !exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 构建BYE消息
    byeMsg := buildByeMessage(deviceID,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    fmt.Println("byeMsg : " + byeMsg)

    // 发送BYE消息
    _, err := s.conn.WriteToUDP([]byte(byeMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send BYE message: %v", err)
    }
    fmt.Printf("BYE message sent to device %s\n", deviceID)

    s.cancel[deviceID]() //关闭接收进程

    // 创建通道用于接收BYE响应
    byeRespChan := make(chan string)

    // 等待并接收BYE响应
    select {
    case response := <-byeRespChan:
        fmt.Printf("Received BYE response from device %s:\n %s\n", deviceID, response)
        if strings.Contains(response, "200 OK") {
            fmt.Printf("音视频流已成功停止在设备 %s\n", deviceID)
        } else {
            return fmt.Errorf("device %s rejected the BYE request: %s", deviceID, response)
        }
    case <-time.After(10 * time.Second): // 设置超时时间为 10 秒
        return fmt.Errorf("timeout waiting for BYE response from device %s", deviceID)
    }

    // 关闭通道
    close(byeRespChan)

    return nil
}

// buildInviteMessage 构建 INVITE 消息
func buildInviteMessage(deviceID, mediaURL string, s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("INVITE sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s:%d;branch=z9hG4bK-123456\r\n",s.devices[deviceID].IP,s.devices[deviceID].Port))
    buffer.WriteString(fmt.Sprintf("From: <sip:%s@%s>;tag=12345\r\n",config.Database.Username,s.devices[deviceID].IP))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@config.Database.Host>\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("Call-ID: %s\r\n", generateCallID()))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 INVITE\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Type: application/sdp\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(mediaURL)))
    buffer.WriteString(mediaURL)
    return buffer.String()
}

// buildAckMessage 构建 ACK 消息
func buildAckMessage(deviceID, response string) string {
    via := extractHeader(response, "Via:")
    from := extractHeader(response, "From:")
    to := extractHeader(response, "To:")
    callID := extractHeader(response, "Call-ID:")
    //cSeq := extractHeader(response, "CSeq:")
	cSeq := "CSeq: 1 ACK"

    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("ACK sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("%s\r\n", via))
    buffer.WriteString(fmt.Sprintf("%s\r\n", from))
    buffer.WriteString(fmt.Sprintf("%s\r\n", to))
    buffer.WriteString(fmt.Sprintf("%s\r\n", callID))
    buffer.WriteString(fmt.Sprintf("%s\r\n", cSeq))
    buffer.WriteString("Content-Length: 0\r\n\r\n")
    return buffer.String()
}

// startRTPServer 启动 RTP 服务器
func (s *SIPServer) startRTPServer(deviceID string, ctx context.Context) {
    rtpAddr, err := net.ResolveUDPAddr("udp", config.Database.Host+":15060") // RTP 默认端口
    if err != nil {
        fmt.Printf("Failed to resolve RTP address: %v\n", err)
        return
    }

    rtpConn, err := net.ListenUDP("udp", rtpAddr)
    if err != nil {
        fmt.Printf("Failed to start RTP server: %v\n", err)
        return
    }
    defer rtpConn.Close()

    fmt.Printf("RTP server started for device %s on %s\n", deviceID, rtpAddr.String())

    buf := make([]byte, 1500) // RTP 数据包最大长度
    for {
        select {
        case <-ctx.Done():
            fmt.Printf("RTP server for device %s is stopping...\n", deviceID)
            return
        default:
            n, addr, err := rtpConn.ReadFromUDP(buf)
            if err != nil {
                if neterr, ok := err.(net.Error); ok && neterr.Temporary() {
                    continue
                }
                fmt.Printf("Failed to read RTP data: %v\n", err)
                return
            }
            fmt.Printf("Received RTP data from %s: %d bytes\n", addr.String(), n)
            // 这里可以添加对 RTP 数据包的处理逻辑
        }
    }
}

// PTZControl 发送云台控制命令
func (s *SIPServer) PTZControl(targetDeviceID, command string, withResponse bool) error {
    sourceDeviceID := config.Database.Username
    // 检查源设备和目标设备是否存在
    sourceDevice, exists := s.devices[sourceDeviceID]
    if !exists {
        return fmt.Errorf("source device %s not found", sourceDeviceID)
    }
    targetDevice, exists := s.devices[targetDeviceID]
    if !exists {
        return fmt.Errorf("target device %s not found", targetDeviceID)
    }

    // 1. 源设备向 SIP 服务器发送云台控制命令
    // ptzMsgFromSource := buildPTZMessage(sourceDeviceID, targetDeviceID, command)
    // fmt.Printf("Source device %s sends PTZ control command to SIP server\n", sourceDeviceID)

    // // 2. SIP 服务器返回 200 OK 给源设备
    // responseToSource := buildResponse(ptzMsgFromSource, 200, "OK")
    // _, err := s.conn.WriteToUDP([]byte(responseToSource), &net.UDPAddr{
    //     IP:   net.ParseIP(sourceDevice.IP),
    //     Port: sourceDevice.Port,
    // })
    // if err != nil {
    //     return fmt.Errorf("failed to send 200 OK to source device: %v", err)
    // }
    // fmt.Printf("SIP server sends 200 OK to source device %s\n", sourceDeviceID)

    // 3. SIP 服务器向目标摄像头设备发送云台控制命令
    ptzMsgToTarget := buildPTZMessage(sourceDeviceID, targetDeviceID, command)
    _, err := s.conn.WriteToUDP([]byte(ptzMsgToTarget), &net.UDPAddr{
        IP:   net.ParseIP(targetDevice.IP),
        Port: targetDevice.Port,
    })
    if err != nil {
        return fmt.Errorf("failed to send PTZ control message to target device: %v", err)
    }
    fmt.Printf("SIP server sends PTZ control command to target device %s %s:%d \n", targetDeviceID,targetDevice.IP,targetDevice.Port)
	fmt.Println("\n send ptz cmd : \n"+ptzMsgToTarget)

    // 4. 接收目标摄像头设备的响应
    buf := make([]byte, 1024)
    n, addr, err := s.conn.ReadFromUDP(buf)
    if err != nil {
        return fmt.Errorf("failed to read response from target device: %v", err)
    }
    responseFromTarget := string(buf[:n])
    fmt.Printf("Received response from target device %s: %s\n", addr.String(), responseFromTarget)

    // 5. 解析目标摄像头设备的响应
	trimmedResponse := strings.TrimSpace(responseFromTarget)
    if strings.Contains(trimmedResponse, "SIP/2.0 200 OK") {
        fmt.Printf("Target device %s successfully processed PTZ control command\n", targetDeviceID)
    } else {
        return fmt.Errorf("target device %s failed to process PTZ control command: %s", targetDeviceID, responseFromTarget)
    }

    // 有应答流程
    if withResponse {
        // 6. 目标摄像头设备向 SIP 服务器发送设备控制响应命令
        // 这里假设摄像头会发送一个 XML 格式的响应
        responseCommand := buildPTZResponseCommand(targetDeviceID, command)
        responseMsgFromTarget := buildPTZResponseMessage(targetDeviceID, sourceDeviceID, responseCommand)
        _, err := s.conn.WriteToUDP([]byte(responseMsgFromTarget), &net.UDPAddr{
            IP:   net.ParseIP(targetDevice.IP),
            Port: targetDevice.Port,
        })
        if err != nil {
            return fmt.Errorf("failed to send PTZ response message from target device: %v", err)
        }
        fmt.Printf("Target device %s sends PTZ response command to SIP server\n", targetDeviceID)

        // 7. SIP 服务器返回 200 OK 给目标摄像头设备
        responseToTarget := buildResponse(responseMsgFromTarget, 200, "OK")
        _, err = s.conn.WriteToUDP([]byte(responseToTarget), &net.UDPAddr{
            IP:   net.ParseIP(targetDevice.IP),
            Port: targetDevice.Port,
        })
        if err != nil {
            return fmt.Errorf("failed to send 200 OK to target device: %v", err)
        }
        fmt.Printf("SIP server sends 200 OK to target device %s\n", targetDeviceID)

        // 8. SIP 服务器向源设备转发设备控制响应命令
        forwardMsg := buildPTZResponseMessage(targetDeviceID, sourceDeviceID, responseCommand)
        _, err = s.conn.WriteToUDP([]byte(forwardMsg), &net.UDPAddr{
            IP:   net.ParseIP(sourceDevice.IP),
            Port: sourceDevice.Port,
        })
        if err != nil {
            return fmt.Errorf("failed to forward PTZ response message to source device: %v", err)
        }
        fmt.Printf("SIP server forwards PTZ response command to source device %s\n", sourceDeviceID)

        // 9. 接收源设备的响应
        n, addr, err = s.conn.ReadFromUDP(buf)
        if err != nil {
            return fmt.Errorf("failed to read response from source device: %v", err)
        }
        responseToSource := string(buf[:n])
        fmt.Printf("Received response from source device %s: %s\n", addr.String(), responseToSource)

        // 10. 解析源设备的响应
        if strings.Contains(responseToSource, "SIP/2.0 200 OK") {
            fmt.Printf("Source device %s successfully received PTZ response\n", sourceDeviceID)
        } else {
            return fmt.Errorf("source device %s failed to receive PTZ response: %s", sourceDeviceID, responseToSource)
        }
    }

    return nil
}

// buildPTZMessage 构建云台控制消息
func buildPTZMessage(sourceDeviceID, targetDeviceID, command string) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("MESSAGE sip:%s SIP/2.0\r\n", targetDeviceID))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s\r\n", sourceDeviceID))
    buffer.WriteString(fmt.Sprintf("From: <sip:%s>\r\n", sourceDeviceID))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s>\r\n", targetDeviceID))
    buffer.WriteString(fmt.Sprintf("Call-ID: %s\r\n", generateCallID()))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 MESSAGE\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Type: Application/MANSCDP+xml\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(command)))
    buffer.WriteString(command)
    return buffer.String()
}

// buildPTZResponseMessage 构建云台控制响应消息
func buildPTZResponseMessage(sourceDeviceID, targetDeviceID, responseCommand string) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("MESSAGE sip:%s SIP/2.0\r\n", targetDeviceID))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s\r\n", sourceDeviceID))
    buffer.WriteString(fmt.Sprintf("From: <sip:%s>\r\n", sourceDeviceID))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s>\r\n", targetDeviceID))
    buffer.WriteString(fmt.Sprintf("Call-ID: %s\r\n", generateCallID()))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 MESSAGE\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Type: Application/MANSCDP+xml\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(responseCommand)))
    buffer.WriteString(responseCommand)
    return buffer.String()
}

// buildPTZResponseCommand 构建云台控制响应命令
func buildPTZResponseCommand(deviceID, command string) string {
    return fmt.Sprintf(`<Control>
    <CmdType>DeviceControlResponse</CmdType>
    <SN>1</SN>
    <DeviceID>%s</DeviceID>
    <Result>Success</Result>
</Control>`, deviceID)
}

// generateCallID 生成一个随机的 Call-ID
func generateCallID() string {
    return fmt.Sprintf("%d@gb28181", time.Now().UnixNano())
}

func (s *SIPServer) Options(deviceID string) error {
    device, exists := s.devices[deviceID]
    if !exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 构建 OPTIONS 消息
    optionsMsg := buildOptionsMessage(deviceID,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    fmt.Println("optionsMsg : " + optionsMsg)

    // 发送 OPTIONS 消息
    _, err := s.conn.WriteToUDP([]byte(optionsMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send OPTIONS message: %v", err)
    }
    fmt.Printf("OPTIONS message sent to device %s\n", deviceID)

    // 创建通道用于接收 OPTIONS 响应
	s.inviteRespChan = make(chan string)

    // 等待并接收 OPTIONS 响应
    select {
    case response := <-s.optionsRespChan:
        fmt.Printf("Received OPTIONS response from device %s:\n %s\n", deviceID, response)
        // 解析响应以获取设备支持的媒体类型
        // 这里可以添加解析逻辑
    case <-time.After(10 * time.Second): // 设置超时时间为 10 秒
        return fmt.Errorf("timeout waiting for OPTIONS response from device %s", deviceID)
    }

    // 关闭通道
    close(s.optionsRespChan)
    s.optionsRespChan = nil

    return nil
}

func buildOptionsMessage(deviceID string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("OPTIONS sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s:%d;branch=z9hG4bK-123456\r\n",s.devices[deviceID].IP,s.devices[deviceID].Port))
    buffer.WriteString(fmt.Sprintf("From: <sip:"+config.Database.Username+"@"+s.devices[deviceID].IP+">;tag=12345\r\n"))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@config.Database.Host>\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("Call-ID: %s\r\n", generateCallID()))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 OPTIONS\r\n"))
    buffer.WriteString("Content-Length: 0\r\n\r\n")
    return buffer.String()
}

// VoiceInvite 发起语音广播请求
func (s *SIPServer) VoiceInvite(deviceID, mediaURL string) error {

    device, exists := s.devices[deviceID]
    if !exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 1. 发送查询消息
    queryMsg := buildQueryMessage(deviceID,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    fmt.Println("queryMsg : " + queryMsg)

    // 发送查询消息
    _, err := s.conn.WriteToUDP([]byte(queryMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send query message: %v", err)
    }
    fmt.Printf("Query message sent to device %s\n", deviceID)

    // 创建通道用于接收查询响应
    s.messageRespChan = make(chan string)

    // 等待并接收查询响应
    select {
    case response := <-s.messageRespChan:
        fmt.Printf("Received query response from device %s:\n %s\n", deviceID, response)

        // 检查响应是否为 200 OK
        if !strings.Contains(response, "200 OK") {
            return fmt.Errorf("device %s rejected the query request: %s", deviceID, response)
        }
    case <-time.After(10 * time.Second): // 设置超时时间为 10 秒
        return fmt.Errorf("timeout waiting for query response from device %s", deviceID)
    }

    // 2. 等待摄像头发送的响应
    recordListChan := make(chan string)
    go func() {
        for {
            select {
            case response := <-s.messageRespChan:
                if strings.Contains(response, "Application/MANSCDP+xml") && strings.Contains(response, "<CmdType>Broadcast</CmdType>") {
                    recordListChan <- response
                    // 发送 200 OK 响应
                    okMsg := buildOKMessage(response)
                    _, err = s.conn.WriteToUDP([]byte(okMsg), addr)
                    if err != nil {
                        fmt.Printf("Failed to send 200 OK message: %v\n", err)
                    }
                    break
                }
            }
        }
    }()

    // 等待摄像头返回记录信息，超时时间为 10 秒
    select {
    case recordList := <-recordListChan:
        fmt.Printf("Received RecordList from device %s:\n %s\n", deviceID, recordList)
    case <-time.After(10 * time.Second):
        return fmt.Errorf("timeout waiting for RecordList from device %s", deviceID)
    }

    // 3. 等待摄像头发起的语音下发 INVITE 请求
    s.inviteRespChan = make(chan string)
    inviteChan := make(chan string)
    go func() {
        for {
            select {
                case response := <-s.inviteRespChan:
                    if strings.Contains(response, "INVITE") {
                        inviteChan <- response
                        break
                    }
                }
        }
    }()

    // 等待 INVITE 请求，超时时间为 10 秒
    select {
    case invite := <-inviteChan:
        fmt.Printf("Received INVITE request from device %s:\n %s\n", deviceID, invite)

        // 发送 100 Trying 响应
        tryMsg := buildTryingMessage(invite)
        _, err = s.conn.WriteToUDP([]byte(tryMsg), addr)
        if err != nil {
            return fmt.Errorf("failed to send 100 Trying message: %v", err)
        }
        fmt.Printf("100 Trying message sent to device %s\n", deviceID)

        // 发送 200 OK 响应
        okMsg := buildOKMessage(invite)
        _, err = s.conn.WriteToUDP([]byte(okMsg), addr)
        if err != nil {
            return fmt.Errorf("failed to send 200 OK message: %v", err)
        }
        fmt.Printf("200 OK message sent to device %s\n", deviceID)

        // 测试提取音频端口
        port := extractAudioPort(invite)
        if port == 0 {
            return fmt.Errorf("failed to extract audio port from INVITE request")
        }

        // 发送音频数据
        audioAddr := &net.UDPAddr{
            IP:   net.ParseIP(device.IP),
            Port: port,
        }
        _, err = s.conn.WriteToUDP([]byte("Audio data"), audioAddr)
        if err != nil {
            return fmt.Errorf("failed to send audio data: %v", err)
        }
        fmt.Printf("Audio data sent to device %s on port %d\n", deviceID, port)

        // 等待 ACK 消息
        s.ackRespChan = make(chan string)
        ackChan := make(chan string)
        go func() {
            for {
                select {
                case response := <-s.ackRespChan:
                    if strings.Contains(response, "ACK") {
                        ackChan <- response
                        break
                    }
                }
            }
        }()

        // 等待 ACK 消息，超时时间为 10 秒
        select {
        case ack := <-ackChan:
            fmt.Printf("Received ACK message from device %s:\n %s\n", deviceID, ack)

            // 发送 200 OK 响应
            okMsg := buildOKMessage(ack)
            _, err = s.conn.WriteToUDP([]byte(okMsg), addr)
            if err != nil {
                return fmt.Errorf("failed to send 200 OK message after ACK: %v", err)
            }
            fmt.Printf("200 OK message sent to device %s after ACK\n", deviceID)

            // // 提取音频端口
            // port := extractAudioPort(invite)
            // if port == 0 {
            //     return fmt.Errorf("failed to extract audio port from INVITE request")
            // }

            // // 发送音频数据
            // audioAddr := &net.UDPAddr{
            //     IP:   net.ParseIP(device.IP),
            //     Port: port,
            // }
            // _, err = s.conn.WriteToUDP([]byte("Audio data"), audioAddr)
            // if err != nil {
            //     return fmt.Errorf("failed to send audio data: %v", err)
            // }
            // fmt.Printf("Audio data sent to device %s on port %d\n", deviceID, port)
        case <-time.After(10 * time.Second):
            return fmt.Errorf("timeout waiting for ACK message from device %s", deviceID)
        }
    case <-time.After(10 * time.Second):
        return fmt.Errorf("timeout waiting for INVITE request from device %s", deviceID)
    }

    // 8. 关闭通道
    close(s.inviteRespChan)
    s.inviteRespChan = nil

    return nil
}

// Bye 结束语音广播会话
func (s *SIPServer) Bye(deviceID string) error {
    device, exists := s.devices[deviceID]
    if !exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 1. 构建 BYE 消息
    byeMsg := buildByeMessage(deviceID,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    fmt.Println("byeMsg : " + byeMsg)

    // 2. 发送 BYE 消息
    _, err := s.conn.WriteToUDP([]byte(byeMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send BYE message: %v", err)
    }
    fmt.Printf("BYE message sent to device %s\n", deviceID)

    // 等待 200 OK 响应
    byeRespChan := make(chan string)
    go func() {
        for {
            buf := make([]byte, 2048)
            n, _, err := s.conn.ReadFromUDP(buf)
            if err != nil {
                fmt.Printf("Failed to read BYE response: %v\n", err)
                return
            }
            response := string(buf[:n])
            if strings.Contains(response, "200 OK") {
                byeRespChan <- response
                break
            }
        }
    }()

    // 等待 200 OK 响应，超时时间为 10 秒
    select {
    case response := <-byeRespChan:
        fmt.Printf("Received 200 OK response for BYE from device %s:\n %s\n", deviceID, response)
    case <-time.After(10 * time.Second):
        return fmt.Errorf("timeout waiting for 200 OK response for BYE from device %s", deviceID)
    }

    return nil
}

// buildQueryMessage 构建查询消息
func buildQueryMessage(deviceID string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString("MESSAGE sip:340100132000000001@"+config.Database.Area+" SIP/2.0\r\n")
    buffer.WriteString("Via: SIP/2.0/UDP "+config.Database.Host+":"+string(s.devices[deviceID].Port)+";branch=z9h64bKRZTzc0Qss3cboTC2itWnZYgv;rport\r\n")
    buffer.WriteString("From: <sip:"+config.Database.Username+"@"+config.Database.Host+":"+string(config.Database.Port)+">;tag=4017925891\r\n")
    buffer.WriteString("To: <sip:"+deviceID+"@"+config.Database.Area+">\r\n")
    buffer.WriteString("Call-ID: ZNnCy2JCd7THaVvtly3F8w2OiCi5Km61\r\n")
    buffer.WriteString("CSeq: 62 MESSAGE\r\n")
    buffer.WriteString("Content-Type: Application/MANSCDP+xml\r\n")
    buffer.WriteString("Max-Forwards: 70\r\n")
    buffer.WriteString("User-Agent: TSINGSEE\r\n")
    buffer.WriteString("X-GB-Ver: 3.0\r\n")

    xml := fmt.Sprintf(`<?xml version="1.0" encoding="GB2312"?>
<Notify>
<CmdType>Broadcast</CmdType>
<SN>10033</SN>
<SourceID>%s</SourceID>
<TargetID>%s</TargetID>
</Notify>`,config.Database.Username, deviceID)

    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(xml)))
    buffer.WriteString(xml)

    return buffer.String()
}

// buildTryingMessage 构建 100 Trying 响应消息
func buildTryingMessage(response string) string {
    var buffer bytes.Buffer
    buffer.WriteString("SIP/2.0 100 Trying\r\n")
    // 提取 Via、From、To、Call-ID、CSeq 等信息
    via := extractHeader(response, "Via")
    from := extractHeader(response, "From")
    to := extractHeader(response, "To")
    callID := extractHeader(response, "Call-ID")
    cseq := extractHeader(response, "CSeq")

    buffer.WriteString(via + "\r\n")
    buffer.WriteString(from + "\r\n")
    buffer.WriteString(to + "\r\n")
    buffer.WriteString(callID + "\r\n")
    buffer.WriteString(cseq + "\r\n")
    buffer.WriteString("User-Agent: TSINGSEE\r\n")
    buffer.WriteString("Content-Length: 0\r\n\r\n")

    return buffer.String()
}

// extractAudioPort 提取 INVITE 请求中的音频端口
func extractAudioPort(invite string) int {
    lines := strings.Split(invite, "\r\n")
    for _, line := range lines {
        if strings.HasPrefix(line, "m=audio") {
            parts := strings.Fields(line)
            if len(parts) >= 2 {
                var port int
                fmt.Sscanf(parts[1], "%d", &port)
                return port
            }
        }
    }
    return 0
}


// startMediaServer 模拟媒体服务器发送音频数据
func (s *SIPServer) startMediaServer(deviceID, mediaURL string) {
    device, exists := s.devices[deviceID]
    if!exists {
        fmt.Printf("device %s not found", deviceID)
        return
    }

    // 解析媒体 URL 中的端口信息
    port := 5004 // 假设默认端口为 5004
    // 这里可以添加更复杂的解析逻辑

    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: port,
    }

    // 模拟发送音频数据
    for i := 0; i < 10; i++ {
        audioData := []byte("Audio data packet")
        _, err := s.conn.WriteToUDP(audioData, addr)
        if err != nil {
            fmt.Printf("Failed to send audio data to device %s: %v", deviceID, err)
        }
        time.Sleep(1 * time.Second)
    }
}

// buildVoiceInviteMessage 构建 INVITE 消息
func buildVoiceInviteMessage(deviceID, mediaURL string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("INVITE sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s:%d;branch=z9hG4bK87654321\r\n",config.Database.Host,config.Database.Port))
    buffer.WriteString(fmt.Sprintf("From: <sip:%s@%s>;tag=77777\r\n",config.Database.Area,config.Database.Host))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@%s>\r\n", deviceID,s.devices[deviceID].IP))
    buffer.WriteString(fmt.Sprintf("Call-ID: 9876543210@%s\r\n",config.Database.Host))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 INVITE\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Type: application/sdp\r\n"))
    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(mediaURL)))
    buffer.WriteString(mediaURL)
    return buffer.String()
}

// buildVoiceAckMessage 构建 ACK 消息
func buildVoiceAckMessage(deviceID, response string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("ACK sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s:%d;branch=z9hG4bK87654321\r\n",s.devices[deviceID].IP,s.devices[deviceID].Port))
    buffer.WriteString(fmt.Sprintf("From: <sip:"+config.Database.Area+"@"+config.Database.Host+">;tag=77777\r\n"))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@"+s.devices[deviceID].IP+">;tag=88888\r\n", deviceID))
    buffer.WriteString(fmt.Sprintf("Call-ID: 9876543210@"+config.Database.Host+"\r\n"))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 ACK\r\n"))
    buffer.WriteString("Content-Length: 0\r\n\r\n")
    return buffer.String()
}

// buildByeMessage 构建 BYE 消息
func buildByeMessage(deviceID string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("BYE sip:%s@%s:%d SIP/2.0\r\n",config.Database.Username,config.Database.Host,config.Database.Port))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s:%d;rport=%d;branch=z9hG4bK54321\r\n",config.Database.Host,config.Database.Port,config.Database.Port))
    buffer.WriteString(fmt.Sprintf("From: <sip:%s@%s:%d>;tag=77777\r\n",config.Database.Username,config.Database.Host,config.Database.Port))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@%s>;tag=88888\r\n", deviceID,s.devices[deviceID].IP))
    buffer.WriteString(fmt.Sprintf("Call-ID: 9876543211@%s\r\n",config.Database.Host))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 BYE\r\n"))
    buffer.WriteString(fmt.Sprintf("Contact: <sip:%s@%s:%d>\r\n\r\n",config.Database.Username,config.Database.Host,config.Database.Port))//
    //buffer.WriteString("Content-Length: 0\r\n\r\n")
    return buffer.String()
}


// TakePicture 发起图片抓拍请求
func (s *SIPServer) TakePicture(deviceID string) error {
    device, exists := s.devices[deviceID]
    if !exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 1. 构建 MESSAGE 请求消息
    messageMsg := buildMessageRequest(deviceID,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    fmt.Println("messageMsg : " + messageMsg)

    // 2. 发送 MESSAGE 请求消息
    _, err := s.conn.WriteToUDP([]byte(messageMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send MESSAGE request: %v", err)
    }
    fmt.Printf("MESSAGE request sent to device %s\n", deviceID)

    // 3. 创建通道用于接收 MESSAGE 响应
    s.messageRespChan = make(chan string)

    // 4. 等待并接收 MESSAGE 响应
    select {
    case response := <-s.messageRespChan:
        fmt.Printf("Received MESSAGE response from device %s:\n %s\n", deviceID, response)

        // 5. 解析响应结果
        result, err := parseMessageResponse(response)
        if err != nil {
            return fmt.Errorf("failed to parse MESSAGE response: %v", err)
        }

        if result.Result == "OK" {
            fmt.Printf("Picture taken successfully. URL: %s\n", result.PictureURL)
            // 可以在这里添加下载图片的逻辑
        } else {
            return fmt.Errorf("picture taking failed. Reason: %s", result.Reason)
        }
    case <-time.After(10 * time.Second): // 设置超时时间为 10 秒
        return fmt.Errorf("timeout waiting for MESSAGE response from device %s", deviceID)
    }

    // 6. 关闭通道
    close(s.messageRespChan)
    s.messageRespChan = nil

    return nil
}

// buildMessageRequest 构建 MESSAGE 请求消息
func buildMessageRequest(deviceID string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("MESSAGE sip:%s@%s SIP/2.0\r\n",s.devices[deviceID].IP, deviceID))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s:%d;branch=z9hG4bK87654321\r\n",config.Database.Host,config.Database.Area))
    buffer.WriteString(fmt.Sprintf("From: <sip:%s@%s>;tag=77777\r\n",config.Database.Area,config.Database.Host))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@%s>\r\n",s.devices[deviceID].IP, deviceID))
    buffer.WriteString(fmt.Sprintf("Call-ID: 9876543210@%s\r\n",config.Database.Host))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 MESSAGE\r\n"))
    buffer.WriteString("Content-Type: Application/MANSCDP+xml\r\n")

    xmlBody := `<?xml version="1.0" encoding="UTF-8"?>
<Control>
    <CmdType>DeviceControl</CmdType>
    <SN>123456</SN>
    <DeviceID>%s</DeviceID>
    <CtrlType>TakePicture</CtrlType>
</Control>`
    xmlBody = fmt.Sprintf(xmlBody, deviceID)
    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(xmlBody)))
    buffer.WriteString(xmlBody)

    return buffer.String()
}

// parseMessageResponse 解析 MESSAGE 响应消息
func parseMessageResponse(response string) (*PictureResponse, error) {
    start := strings.Index(response, "<?xml")
    if start == -1 {
        return nil, fmt.Errorf("XML body not found in response")
    }
    xmlBody := response[start:]

    var result PictureResponse
    err := xml.Unmarshal([]byte(xmlBody), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to unmarshal XML response: %v", err)
    }

    return &result, nil
}

// PictureResponse 表示图片抓拍响应结构体
type PictureResponse struct {
    CmdType    string `xml:"CmdType"`
    SN         string `xml:"SN"`
    DeviceID   string `xml:"DeviceID"`
    Result     string `xml:"Result"`
    PictureURL string `xml:"PictureURL"`
    Reason     string `xml:"Reason"`
}

//网络设备信息查询
// 发送 MESSAGE 请求并等待响应
func (s *SIPServer) SendMessageRequest(deviceID string, cmdType string, xmlBody string) (string, error) {
    device, exists := s.devices[deviceID]
    if!exists {
        return "", fmt.Errorf("device %s not found", deviceID)
    }

    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("MESSAGE sip:%s@%s:%d SIP/2.0\r\n", deviceID, device.IP, device.Port))
    buffer.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s:%d;branch=z9hG4bK87654321\r\n",config.Database.Host,config.Database.Port))
    buffer.WriteString(fmt.Sprintf("From: <sip:%s@%s>;tag=77777\r\n",config.Database.Area,config.Database.Host))
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@%s:%d>\r\n", deviceID, device.IP, device.Port))
    buffer.WriteString(fmt.Sprintf("Call-ID: 9876543210@%s\r\n",config.Database.Host))
    buffer.WriteString(fmt.Sprintf("CSeq: 1 MESSAGE\r\n"))
    buffer.WriteString("Content-Type: Application/MANSCDP+xml\r\n")
    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(xmlBody)))
    buffer.WriteString(xmlBody)

    messageMsg := buffer.String()
    fmt.Println("messageMsg : " + messageMsg)

    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    _, err := s.conn.WriteToUDP([]byte(messageMsg), addr)
    if err != nil {
        return "", fmt.Errorf("failed to send MESSAGE request: %v", err)
    }
    fmt.Printf("MESSAGE request sent to device %s\n", deviceID)

    s.messageRespChan = make(chan string)
    select {
    case response := <-s.messageRespChan:
        fmt.Printf("Received MESSAGE response from device %s:\n%s\n", deviceID, response)
        //return response, nil
    case <-time.After(10 * time.Second):
        return "", fmt.Errorf("timeout waiting for MESSAGE response from device %s", deviceID)
    }

    select {
    case response := <-s.messageRespChan:
        fmt.Printf("Received MESSAGE XML response from device %s:\n%s\n", deviceID, response)
        s.ParseFrontEndDeviceInfoResponse(response)
        //return response, nil
    case <-time.After(10 * time.Second):
        return "", fmt.Errorf("timeout waiting for MESSAGE XML  response from device %s", deviceID)
    }

    close(s.messageRespChan)
    s.messageRespChan = nil

    return "",fmt.Errorf("success get MESSAGE XML  response from device %s", deviceID)
}

// 解析设备信息查询响应
type DeviceInfoResponse struct {
    CmdType    string `xml:"CmdType"`
    SN         string `xml:"SN"`
    DeviceID   string `xml:"DeviceID"`
    Result     string `xml:"Result"`
    DeviceInfo struct {
        Model        string `xml:"Model"`
        SoftwareVersion string `xml:"SoftwareVersion"`
        IPAddress    string `xml:"IPAddress"`
        MACAddress   string `xml:"MACAddress"`
    } `xml:"DeviceInfo"`
}

func  (s *SIPServer)  ParseDeviceInfoResponse(response string) (*DeviceInfoResponse, error) {
    var result DeviceInfoResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse DeviceInfo response: %v", err)
    }
    return &result, nil
}

// 解析前端设备信息查询响应
type FrontEndDeviceInfoResponse struct {
    CmdType    string `xml:"CmdType"`
    SN         string `xml:"SN"`
    DeviceID   string `xml:"DeviceID"`
    Result     string `xml:"Result"`
    DeviceName string `xml:"DeviceName"`
    Manufacturer string `xml:"Manufacturer"`
    Model      string `xml:"Model"`
    Firmware   string `xml:"Firmware"`
    Channel    string `xml:"Channel"`
}

func  (s *SIPServer)  ParseFrontEndDeviceInfoResponse(response string) (*FrontEndDeviceInfoResponse, error) {

    xmlPart := extractXML(response)
    if xmlPart == "" {
        fmt.Println("No XML part found in the SIP message")
        return nil, fmt.Errorf("failed to parse FrontEndDeviceInfo response ")
    }

    var result FrontEndDeviceInfoResponse
    err := xml.Unmarshal([]byte(xmlPart), &result)
    if err != nil {
        fmt.Println("ParseFrontEndDeviceInfoResponse error ")
        return nil, fmt.Errorf("failed to parse FrontEndDeviceInfo response: %v", err)
    }
    fmt.Println("ParseFrontEndDeviceInfoResponse")
    fmt.Println(result)

    s.platfrom[result.DeviceID] = &device.DevicePlatfrom{
		ID:     result.DeviceID,
		DeviceName:     result.DeviceName,
		Manufacturer:   result.Manufacturer,
		Model: result.Model,
        Firmware: result.Firmware,
	}

    user := device.DeviceBasic{}
    data := device.FindDeviceByName(result.DeviceID)
	// id, _ := strconv.Atoi(c.PostForm("id"))
	user.ID = uint(data.ID) 
    user.DeviceID = result.DeviceID
	user.DeviceName = s.platfrom[result.DeviceID].DeviceName
	user.Manufacturer = s.platfrom[result.DeviceID].Manufacturer
	user.ModelType = s.platfrom[result.DeviceID].Model
	user.Firmware = s.platfrom[result.DeviceID].Firmware

	device.UpdateDevice(user)

    return &result, nil
}

func extractXML(sipMessage string) string {
    startIndex := strings.Index(sipMessage, "<?xml")
    if startIndex == -1 {
        return ""
    }
    return sipMessage[startIndex:]
}

// 解析前端设备状态信息查询响应
type FrontEndDeviceStatusResponse struct {
    CmdType    string `xml:"CmdType"`
    SN         string `xml:"SN"`
    DeviceID   string `xml:"DeviceID"`
    Result     string `xml:"Result"`
    Online     string `xml:"Online"`
    Status     string `xml:"Status"`
    DeviceTime string `xml:"DeviceTime"`
    Alarmstatus struct {
        Num string `xml:"Num,attr"`
    } `xml:"Alarmstatus"`
    Encode string `xml:"Encode"`
}

func  (s *SIPServer)  ParseFrontEndDeviceStatusResponse(response string) (*FrontEndDeviceStatusResponse, error) {
    var result FrontEndDeviceStatusResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse FrontEndDeviceStatus response: %v", err)
    }
    return &result, nil
}

// 解析设备配置查询响应
type DeviceConfigResponse struct {
    CmdType    string `xml:"CmdType"`
    SN         string `xml:"SN"`
    DeviceID   string `xml:"DeviceID"`
    Result     string `xml:"Result"`
    Config     struct {
        VideoCodec string `xml:"VideoCodec"`
        Resolution string `xml:"Resolution"`
        FrameRate  string `xml:"FrameRate"`
    } `xml:"Config"`
}

func  (s *SIPServer) ParseDeviceConfigResponse(response string) (*DeviceConfigResponse, error) {
    var result DeviceConfigResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse DeviceConfig response: %v", err)
    }
    return &result, nil
}

// 解析预置位查询响应
type PresetPositionResponse struct {
    CmdType  string `xml:"CmdType"`
    SN       string `xml:"SN"`
    DeviceID string `xml:"DeviceID"`
    Result   string `xml:"Result"`
    Presets  []struct {
        PresetID string `xml:"PresetID"`
        PositionX string `xml:"PositionX"`
        PositionY string `xml:"PositionY"`
        Zoom      string `xml:"Zoom"`
    } `xml:"Presets>Preset"`
}

func  (s *SIPServer)  ParsePresetPositionResponse(response string) (*PresetPositionResponse, error) {
    var result PresetPositionResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse PresetPosition response: %v", err)
    }
    return &result, nil
}

// 解析看守位信息查询响应
type GuardPositionResponse struct {
    CmdType  string `xml:"CmdType"`
    SN       string `xml:"SN"`
    DeviceID string `xml:"DeviceID"`
    Result   string `xml:"Result"`
    GuardPosition struct {
        PositionX string `xml:"PositionX"`
        PositionY string `xml:"PositionY"`
        Zoom      string `xml:"Zoom"`
    } `xml:"GuardPosition"`
}

func  (s *SIPServer)  ParseGuardPositionResponse(response string) (*GuardPositionResponse, error) {
    var result GuardPositionResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse GuardPosition response: %v", err)
    }
    return &result, nil
}

// 解析巡航轨迹列表查询响应
type CruiseTrackListResponse struct {
    CmdType  string `xml:"CmdType"`
    SN       string `xml:"SN"`
    DeviceID string `xml:"DeviceID"`
    Result   string `xml:"Result"`
    // 这里可以根据实际响应结构扩展
}

func  (s *SIPServer)  ParseCruiseTrackListResponse(response string) (*CruiseTrackListResponse, error) {
    var result CruiseTrackListResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse CruiseTrackList response: %v", err)
    }
    return &result, nil
}

// CruiseTrackQueryResponse 定义巡航轨迹查询响应的结构体
type CruiseTrackQueryResponse struct {
    CmdType  string `xml:"CmdType"`
    SN       string `xml:"SN"`
    DeviceID string `xml:"DeviceID"`
    Result   string `xml:"Result"`
    TrackInfo struct {
        StartPoint string   `xml:"StartPoint"`
        EndPoint   string   `xml:"EndPoint"`
        Speed      string   `xml:"Speed"`
        Points     []string `xml:"Points>Point"`
    } `xml:"TrackInfo"`
}

// ParseCruiseTrackQueryResponse 解析巡航轨迹查询响应
func (s *SIPServer) ParseCruiseTrackQueryResponse(response string) (*CruiseTrackQueryResponse, error) {
    var result CruiseTrackQueryResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse CruiseTrackQuery response: %v", err)
    }
    return &result, nil
}

// PTZAccurateStatusQueryResponse 定义 PTZ 精准状态查询响应的结构体
type PTZAccurateStatusQueryResponse struct {
    CmdType  string `xml:"CmdType"`
    SN       string `xml:"SN"`
    DeviceID string `xml:"DeviceID"`
    Result   string `xml:"Result"`
    PTZStatus struct {
        Pan  string `xml:"Pan"`
        Tilt string `xml:"Tilt"`
        Zoom string `xml:"Zoom"`
    } `xml:"PTZStatus"`
}

// ParsePTZAccurateStatusQueryResponse 解析 PTZ 精准状态查询响应
func (s *SIPServer) ParsePTZAccurateStatusQueryResponse(response string) (*PTZAccurateStatusQueryResponse, error) {
    var result PTZAccurateStatusQueryResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse PTZAccurateStatusQuery response: %v", err)
    }
    return &result, nil
}

// MemoryCardStatusQueryResponse 定义存储卡状态查询响应的结构体
type MemoryCardStatusQueryResponse struct {
    CmdType  string `xml:"CmdType"`
    SN       string `xml:"SN"`
    DeviceID string `xml:"DeviceID"`
    Result   string `xml:"Result"`
    MemoryCardInfo struct {
        Status     string `xml:"Status"`
        Capacity   string `xml:"Capacity"`
        UsedSpace  string `xml:"UsedSpace"`
    } `xml:"MemoryCardInfo"`
}

// ParseMemoryCardStatusQueryResponse 解析存储卡状态查询响应
func (s *SIPServer) ParseMemoryCardStatusQueryResponse(response string) (*MemoryCardStatusQueryResponse, error) {
    var result MemoryCardStatusQueryResponse
    err := xml.Unmarshal([]byte(response), &result)
    if err != nil {
        return nil, fmt.Errorf("failed to parse MemoryCardStatusQuery response: %v", err)
    }
    return &result, nil
}

//历史
// HistoryInvite 发起历史视音频回放请求
func (s *SIPServer) HistoryInvite(deviceID, startTime, endTime string) error {
    device, exists := s.devices[deviceID]
    if!exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 1. 发起查看历史回放信息
    recordInfoMsg := buildRecordInfoMessage(deviceID, startTime, endTime,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    fmt.Println("recordInfoMsg : " + recordInfoMsg)

    // 发送查看历史回放信息请求
    _, err := s.conn.WriteToUDP([]byte(recordInfoMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send RecordInfo message: %v", err)
    }
    fmt.Printf("RecordInfo message sent to device %s\n", deviceID)

    // 创建通道用于接收 RecordInfo 响应
    s.messageRespChan = make(chan string)

    // 等待并接收 RecordInfo 响应
    select {
    case response := <-s.messageRespChan:
        fmt.Printf("Received RecordInfo response from device %s:\n %s\n", deviceID, response)

        // 检查响应是否为 200 OK
        if!strings.Contains(response, "200 OK") {
            return fmt.Errorf("device %s rejected the RecordInfo request: %s", deviceID, response)
        }
    case <-time.After(10 * time.Second): // 设置超时时间为 10 秒
        return fmt.Errorf("timeout waiting for RecordInfo response from device %s", deviceID)
    }

    // 2. 等待摄像头返回记录信息
    recordListChan := make(chan string)
    go func() {
        for {
            
            response := <-s.messageRespChan
            if strings.Contains(response, "Application/MANSCDP+xml") {
                recordListChan <- response
                // 发送 200 OK 响应
                okMsg := buildOKMessage(response)
                _, err = s.conn.WriteToUDP([]byte(okMsg), addr)
                if err != nil {
                    fmt.Printf("Failed to send 200 OK message: %v\n", err)
                }
            }
        }
    }()

    // 等待摄像头返回记录信息，超时时间为 10 秒
    select {
    case recordList := <-recordListChan:
        fmt.Printf("Received RecordList from device %s:\n %s\n", deviceID, recordList)
        if strings.Contains(recordList, "Cannot get record file") {
            return fmt.Errorf("Cannot get record file from device %s", deviceID)
        }
    case <-time.After(10 * time.Second):
        return fmt.Errorf("timeout waiting for RecordList from device %s", deviceID)
    }

    // 3. 发起视频回放
    // 启动 RTP 服务器接收媒体流
    // rtpConn, err := s.startHistoryRTPServer(deviceID)
    // if err != nil {
    //     return fmt.Errorf("failed to start RTP server: %v", err)
    // }
    // s.rtpServers[deviceID] = rtpConn

    // 构建 INVITE 消息
    inviteMsg := buildHistoryInviteMessage(deviceID, startTime, endTime)
    fmt.Println("inviteMsg : " + inviteMsg)

    // 发送 INVITE 消息
    _, err = s.conn.WriteToUDP([]byte(inviteMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send INVITE message: %v", err)
    }
    fmt.Printf("INVITE message sent to device %s\n", deviceID)

    // 创建通道用于接收 INVITE 响应
    s.inviteRespChan = make(chan string)

    // 等待并接收 INVITE 响应
    select {
    case response := <-s.inviteRespChan:
        fmt.Printf("Received INVITE response from device %s:\n %s\n", deviceID, response)

        // 检查摄像头响应
        if!strings.Contains(response, "200 OK") {
            return fmt.Errorf("device %s rejected the INVITE request: %s", deviceID, response)
        }

        // 发送 ACK 确认消息
        ackMsg := buildHistoryAckMessage(deviceID, response,s)
        _, err = s.conn.WriteToUDP([]byte(ackMsg), addr)
        if err != nil {
            return fmt.Errorf("failed to send ACK message: %v", err)
        }
        fmt.Printf("ACK message sent to device %s\n", deviceID)
        fmt.Println("ackMsg:" + ackMsg)

    case <-time.After(10 * time.Second): // 设置超时时间为 10 秒
        return fmt.Errorf("timeout waiting for INVITE response from device %s", deviceID)
    }

    // 关闭通道
    close(s.inviteRespChan)
    s.inviteRespChan = nil

    // 等待媒体结束通知
    s.mediaEndChan = make(chan string)
    go func() {
        select {
        case <-s.mediaEndChan:
            fmt.Printf("Media playback for device %s has ended.\n", deviceID)
            s.CloseHistoryPlayback(deviceID)
        case <-time.After(3600 * time.Second): // 设置超时时间为 1 小时
            fmt.Printf("Timeout waiting for media end notification from device %s.\n", deviceID)
            s.CloseHistoryPlayback(deviceID)
        }
    }()

    return nil
}

// ClosePlayback 关闭历史视音频回放
func (s *SIPServer) CloseHistoryPlayback(deviceID string) error {
    device, exists := s.devices[deviceID]
    if!exists {
        return fmt.Errorf("device %s not found", deviceID)
    }

    // 发送 BYE 消息
    byeMsg := buildHistoryByeMessage(deviceID,s)
    addr := &net.UDPAddr{
        IP:   net.ParseIP(device.IP),
        Port: device.Port,
    }

    _, err := s.conn.WriteToUDP([]byte(byeMsg), addr)
    if err != nil {
        return fmt.Errorf("failed to send BYE message: %v", err)
    }
    fmt.Printf("BYE message sent to device %s\n", deviceID)

    // 关闭 RTP 服务器
    if rtpConn, ok := s.rtpServers[deviceID]; ok {
        rtpConn.Close()
        delete(s.rtpServers, deviceID)
    }

    return nil
}

// buildRecordInfoMessage 构建查看历史回放信息请求消息
func buildRecordInfoMessage(deviceID, startTime, endTime string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString("MESSAGE sip:340100132000000001@3401000000 SIP/2.0\r\n")
    buffer.WriteString("Via: SIP/2.0/UDP "+config.Database.Host+":"+config.Database.Area+";branch=z9h64bKCn191TkGAPiBtxF7BhD4GMYG;rport\r\n")
    buffer.WriteString("From: <sip:"+config.Database.Username+"@"+config.Database.Host+":"+string(config.Database.Port)+">;tag=3750889793\r\n")
    buffer.WriteString("To: <sip:"+s.devices[deviceID].ID+"@"+config.Database.Area+">\r\n")
    buffer.WriteString("Call-ID: mmCwDCJzoBZKcColHDs9txV96Ct322nG\r\n")
    buffer.WriteString("CSeq: 8 MESSAGE\r\n")
    buffer.WriteString("Content-Type: Application/MANSCDP+xml\r\n")
    buffer.WriteString("Max-Forwards: 70\r\n")
    buffer.WriteString("User-Agent: TSINGSEE\r\n")
    buffer.WriteString("X-GB-Ver: 3.0\r\n")

    xml := fmt.Sprintf(`<?xml version="1.0" encoding="GB2312"?>
<Query>
<CmdType>RecordInfo</CmdType>
<SN>10006</SN>
<DeviceID>%s</DeviceID>
<StartTime>%s</StartTime>
<EndTime>%s</EndTime>
<Type>all</Type>
</Query>`, deviceID, startTime, endTime)

    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(xml)))
    buffer.WriteString(xml)

    return buffer.String()
}

// buildOKMessage 构建 200 OK 响应消息
func buildOKMessage(response string) string {
    var buffer bytes.Buffer
    buffer.WriteString("SIP/2.0 200 OK\r\n")
    // 提取 Via、From、To、Call-ID、CSeq 等信息
    via := extractHeader(response, "Via")
    from := extractHeader(response, "From")
    to := extractHeader(response, "To")
    callID := extractHeader(response, "Call-ID")
    cseq := extractHeader(response, "CSeq")

    buffer.WriteString(via + "\r\n")
    buffer.WriteString(from + "\r\n")
    buffer.WriteString(to + "\r\n")
    buffer.WriteString(callID + "\r\n")
    buffer.WriteString(cseq + "\r\n")
    buffer.WriteString("User-Agent: TSINGSEE\r\n")
    buffer.WriteString("Content-Length: 0\r\n\r\n")

    return buffer.String()
}

// buildHistoryInviteMessage 构建 INVITE 消息
func buildHistoryInviteMessage(deviceID, startTime, endTime string) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("INVITE sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString("Via: SIP/2.0/UDP "+config.Database.Host+":"+string(config.Database.Port)+";branch=z9hG4bK77777\r\n")
    buffer.WriteString("From: <sip:"+config.Database.Username+"@"+config.Database.Host+">;tag=88888\r\n")
    buffer.WriteString(fmt.Sprintf("To: <sip:%s@"+config.Database.Area+">\r\n", deviceID))
    buffer.WriteString("Call-ID: 99999@"+config.Database.Host+"\r\n")
    buffer.WriteString("CSeq: 1 INVITE\r\n")
    buffer.WriteString("Subject: Playback, SourceID="+deviceID+", ReceiverID="+config.Database.Username+"\r\n")
    buffer.WriteString("Content-Type: application/sdp\r\n")

    sdp := fmt.Sprintf(`v=0
o=44011300451322000007 0 0 IN IP4 %s
s=Playback
u=44011300451322000007:0
c=IN IP4 %s
t=%s %s
m=video 30002 TCP/RTP/AVP 96 97 98
a=recvonly
a=setup:passive
a=connection:new
a=rtpmap:96 PS/90000
a=rtpmap:97 MPEG4/90000
a=rtpmap:98 H264/90000
y=1200000002
`,config.Database.Host,config.Database.Host, startTime, endTime)

    buffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(sdp)))
    buffer.WriteString(sdp)

    return buffer.String()
}

// buildHistoryAckMessage 构建 ACK 消息
func buildHistoryAckMessage(deviceID, response string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("ACK sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString("Via: SIP/2.0/UDP "+s.devices[deviceID].IP+":"+string(s.devices[deviceID].Port)+";branch=z9hG4bK77777\r\n")
    buffer.WriteString("From: <sip:"+config.Database.Area+"@"+s.devices[deviceID].IP+">;tag=88888\r\n")
    buffer.WriteString(fmt.Sprintf("To: <sip:%s>\r\n", deviceID))
    buffer.WriteString("Call-ID: 99999@"+s.devices[deviceID].IP+"\r\n")
    buffer.WriteString("CSeq: 1 ACK\r\n")
    buffer.WriteString("Content-Length: 0\r\n\r\n")

    return buffer.String()
}

// buildHistoryByeMessage 构建 BYE 消息
func buildHistoryByeMessage(deviceID string,s *SIPServer) string {
    var buffer bytes.Buffer
    buffer.WriteString(fmt.Sprintf("BYE sip:%s SIP/2.0\r\n", deviceID))
    buffer.WriteString("Via: SIP/2.0/UDP "+s.devices[deviceID].IP+":"+string(s.devices[deviceID].Port)+";branch=z9hG4bK77777\r\n")
    buffer.WriteString("From: <sip:"+config.Database.Area+"@"+s.devices[deviceID].IP+">;tag=88888\r\n")
    buffer.WriteString(fmt.Sprintf("To: <sip:%s>\r\n", deviceID))
    buffer.WriteString("Call-ID: 99999@"+s.devices[deviceID].IP+"\r\n")
    buffer.WriteString("CSeq: 1 BYE\r\n")
    buffer.WriteString("Content-Length: 0\r\n\r\n")

    return buffer.String()
}

// startHistoryRTPServer 启动 RTP 服务器接收媒体流
func (s *SIPServer) startHistoryRTPServer(deviceID string) (*net.UDPConn, error) {
    rtpAddr, err := net.ResolveUDPAddr("udp", ":5004")
    if err != nil {
        return nil, fmt.Errorf("failed to resolve RTP address: %v", err)
    }

    rtpConn, err := net.ListenUDP("udp", rtpAddr)
    if err != nil {
        return nil, fmt.Errorf("failed to listen on RTP port: %v", err)
    }

    fmt.Printf("RTP server started for device %s on port 5004\n", deviceID)

    go func() {
        buffer := make([]byte, 1500)
        for {
            n, addr, err := rtpConn.ReadFromUDP(buffer)
            if err != nil {
                fmt.Printf("Error reading from RTP socket: %v", err)
                continue
            }
            fmt.Printf("Received %d bytes from %s\n", n, addr)
            // 在这里处理接收到的 RTP 包
        }
    }()

    return rtpConn, nil
}

// handleMediaEndNotification 处理媒体结束通知
func (s *SIPServer) handleHistoryMediaEndNotification(msg string) {
    var notify struct {
        CmdType    string `xml:"CmdType"`
        SN         string `xml:"SN"`
        DeviceID   string `xml:"DeviceID"`
        NotifyType string `xml:"NotifyType"`
    }
    err := xml.Unmarshal([]byte(msg), &notify)
    if err != nil {
        fmt.Printf("Failed to parse media end notification: %v", err)
        return
    }

    if notify.NotifyType == "121" {
        s.mediaEndChan <- notify.DeviceID
    }
}
